package online_store.model.dao;

import java.sql.Connection;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import online_store.entity.UserEntity;

@Repository
public class UserDao {
	
	@PersistenceContext(name="online_store-persistence")
	EntityManager em;
	
	public UserEntity getUser(int id){
		UserEntity user = new UserEntity();
		
		Query query = em.createQuery("SELECT user FROM UserEntity user WHERE user.id=:id");
		query.setParameter("id", id);
		user = (UserEntity) query.getSingleResult();
		
		return user;
	}
	
	public UserEntity findByUsername(String username){
		UserEntity user = null;
		
		Query query = em.createQuery("SELECT user FROM UserEntity user WHERE user.username=:username");
		query.setParameter("username", username);
		if(!query.getResultList().isEmpty()){
			user = new UserEntity();
			user = (UserEntity) query.getSingleResult();
		}

		return user;
	}
	
	public void createUser(UserEntity user){
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
	}
	
	public void updateUser(UserEntity user){
		em.getTransaction().begin();
		em.merge(user);
		em.getTransaction().commit();
	}
	
	
}
